﻿using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Common.Filter;
using KingsSharp.Common.Secutiry;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Core.Data.Extensions;
using KingsSharp.Web.Helper;
using KingsSharp.Web.Mvc.Binders;
using KingsSharp.Web.UI;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Data.Entity;

namespace CRM.Admin.Areas.Sys.Controllers
{
    public class UserController : Controller
    {
        /// <summary>
        /// 用户信息契约
        /// </summary>
        public IUserInfoService _userInfoService { get; set; }

        /// <summary>
        /// 角色业务契约
        /// </summary>
        public IRoleService _roleService { get; set; }

        #region 视图功能
        public ActionResult UserIndex()
        {
            return View();
        }
        /// <summary>
        /// 新增视图
        /// </summary>
        /// <returns></returns>
        public ActionResult UserAdd()
        {
            return View();
        }
        /// <summary>
        /// 编辑视图
        /// </summary>
        /// <param name="UserId">用户表主键Id</param>
        /// <returns>返回具体的UserInfoDto对象</returns>
        public ActionResult UserEdit(Guid UserId)
        {
            var dtodata = _userInfoService.ItemUserInfo.Include(a => a.UserRoles).Where(entity => entity.Id == UserId)
                .FirstOrDefault().MapTo<UserInfoDto>();
            if (!string.IsNullOrWhiteSpace(dtodata.RoleIds))
            {
                Guid[] ids = dtodata.RoleIds.Split(',').Select(a => new Guid(a)).ToArray();
                var roledata = _roleService.ItemRole.Where(a => ids.Contains(a.Id)).Select(a => a.Name).ToArray();
                dtodata.RoleNames = string.Join(",", roledata);
            }
            return View(dtodata);
        }
        #endregion


        #region 数据功能
        /// <summary>
        /// 用户数据保存
        /// </summary>
        /// <param name="dtos">用户信息Dto信息</param>
        /// <returns>json业务操作结果</returns>
        [HttpPost]
        public ActionResult UserInsert([ModelBinder(typeof(JsonBinder<UserInfoDto>))] UserInfoDto dtos)
        {
            dtos.CheckNotNull("dtos");
            dtos.Id = Guid.NewGuid();
            dtos.Password = DesHelper.Encrypt(dtos.Password, AppConsts.DES_USER_KEY);
            var result = _userInfoService.InsertUserInfo(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "用户“{0}”添加成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }

        public ActionResult UserUpdate([ModelBinder(typeof(JsonBinder<UserInfoDto>))] UserInfoDto dtos)
        {
            dtos.CheckNotNull("dtos");
            var result = _userInfoService.UpdateUserInfo(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "用户“{0}”更新成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }

        public ActionResult UserDelete(Guid UserId, string UserName)
        {
            var result = _userInfoService.DeleteUserInfo(UserId);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "用户“{0}”删除成功。".FormatWith(UserName);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 分页获取用户信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserInfoGridData()
        {
            GridRequest request = new GridRequest(Request);
            Expression<Func<UserInfo, bool>> predicate = FilterHelper.GetExpression<UserInfo>(request.FilterGroup);
            int total;
            var data = _userInfoService.ItemUserInfo.Include(a => a.UserRoles)
                .Where<UserInfo, Guid>(predicate, request.PageCondition, out total)
                .Where(a => a.IsDeleted == false)
                .ToList();
            return Json(new GridData<object>(data.MapToList<UserInfo, UserInfoDto>(), total), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPwd"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        public ActionResult EditPwd(string oldPwd,string Pwd)
        {
            oldPwd = DesHelper.Encrypt(oldPwd, AppConsts.DES_USER_KEY);
            var entity = _userInfoService.ItemUserInfo.FirstOrDefault(a => a.Id == AppVariable.UserData.UserId);
            if (oldPwd.Equals(entity.Password))
            {              
                entity.Password = DesHelper.Encrypt(Pwd, AppConsts.DES_USER_KEY);
                var result = _userInfoService.UpdateUserPwd(entity);
                AjaxResultType msgType = result.ResultType.ToAjaxResultType();
                if (msgType != AjaxResultType.Error)
                {
                    return Json("1");
                }
                else {
                    return Json("0");
                }
            }
            else {
                return Json("2");
            }
        }

        /// <summary>
        /// 用户头像上传
        /// </summary>
        /// <returns></returns>
        public ActionResult UploaderProcess()
        {
            UploaderResult result = null;
            try
            {
                string path = AppConsts.USER_FILE_BASEPATH + AppVariable.UserData.LoginCode + "//";
                result = new WebUploader().Process(Request, path, file =>
                {
                    return AppVariable.UserData.LoginCode + "_" + file.FileName;
                });
            }
            catch (Exception ex)
            {
                result = new UploaderResult();
                result.Message = ex.Message;
                throw new Exception(ex.Message);
            }
            return Json(result);
        }
        #endregion
    }
}